package com.jushu.storbox.service;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.app.Dialog;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.jushu.storbox.LoginActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.ViewActivity;
import com.jushu.storbox.callback.ICallback;
import com.jushu.storbox.callback.IDownloadCallback;
import com.jushu.storbox.callback.IDownloadThumbnailCallback;
import com.jushu.storbox.callback.IShareDownloadCallback;
import com.jushu.storbox.callback.IUpdateStateChangeListener;
import com.jushu.storbox.callback.IUploadCallback;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.ErrorConstant;
import com.jushu.storbox.constant.ExceptionConstant;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.entities.UploadObject;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.manager.DownloadTaskManager;
import com.jushu.storbox.manager.ShareDownloadTaskManager;
import com.jushu.storbox.manager.UploadTaskManager;
import com.jushu.storbox.task.tqueue.DownloadTask;
import com.jushu.storbox.task.tqueue.ShareDownloadTask;
import com.jushu.storbox.task.tqueue.UploadTask;
import com.jushu.storbox.util.CloudDriveDialogUtil;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PollingAlarmUtils;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.UpgradeUtils;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.model.request.FolderCreateRequest;
import com.huawei.sharedrive.sdk.android.model.response.ADUser;
import com.huawei.sharedrive.sdk.android.modelV2.request.ClientInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderSearchRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.LinkCreateRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderListResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderResponse;
import com.huawei.sharedrive.sdk.android.modelV2.response.LinkInfoV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.RefreshToken;
import com.huawei.sharedrive.sdk.android.modelV2.response.UserInfoV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.UserResponseV2;
import com.huawei.sharedrive.sdk.android.modelV3.response.LinkInfoV3;
import com.huawei.sharedrive.sdk.android.service.CommonClient;
import com.huawei.sharedrive.sdk.android.service.handler.AsyncTaskHandler;
import com.huawei.sharedrive.sdk.android.service.handler.AsyncTaskResponseInterceptor;
import com.huawei.sharedrive.sdk.android.serviceV2.UserClientV2;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

//import android.widget.Toast;

public class CloudDriveService extends Service implements ICloudDriveService
{
    private final IBinder binder = new CenterShareDriveServiceServiceBinder();
    
    private final static String TAG = "CloudDriveService";
    
    private final static int uplodadUpdate = 1007;
    
    UserClientV2 userClient = ShareDriveApplication.getInstance().getUserClientV2();
    
    private IRemoteFileService remoteFileService = null;
    
    private IRemoteFolderService remoteFolderService = null;
    
    private IRemoteINodeService remoteINodeService = null;
    
    private IRemoteMailListService remoteMailListService = null;
    
    private IRemoteShareFileService remoteShareFileService = null;
    
    private IRemoteShareFolderService remoteShareFolderService = null;
    
    private ILocalFileService localFileService = null;
    
    private ILocalShareINodeService localShareINodeService = null;
    
    private IMailListService iMailListService = null;
    
    private IMusicService iMusicService = null;
    
    /** Authen failed 401 */
    private final static int failedToAuthen = 5;
    
    /** refresh Token */
    private final static int refreshToken = 6;
    
    /** unknown exception */
    private final static int networkIsNotAvailible = 7;
    
    /** unknown exception */
    private final static int loginException = 8;
    
    /** internet state */
    private final static int internetState = 4;
    
    /** network broadcast refresh old time */
    private long oldSystemTime = -1;

	private SharedPreferences settings = null;
    
    private final static int sendFromLogin = 1001;
    
    public class CenterShareDriveServiceServiceBinder extends Binder
    {
        public CloudDriveService getService()
        {
            return CloudDriveService.this;
        }
    }
    
    @Override
    public boolean onUnbind(Intent intent)
    {
        LogUtil.i(TAG, "onUnBind");
        if ("tokenAlarm".equals(intent.getAction()))
        {
            IntentFilter filter = new IntentFilter("relogin");
            unregisterReceiver(reloginReceiver);
        }
        // else if("musicPlayer".equals(intent.getAction())){
        // return super.onUnbind(intent);
        // }
        iMusicService.destory();
        shutUpApp();
        return super.onUnbind(intent);
    }
    
    @Override
    public void onDestroy()
    {
        unregisterReceiver(mReceiver);
        // DownloadTaskManager.stop();
        // UploadTaskManager.stop();
        LogUtil.i(TAG, "onDestroy");
        super.onDestroy();
    }
    
    @Override
    public IBinder onBind(Intent intent)
    {
        LogUtil.i(TAG, "onBind");
        if ("tokenAlarm".equals(intent.getAction()))
        {
            IntentFilter filter = new IntentFilter("relogin");
            registerReceiver(reloginReceiver, filter);
        }
	    
        return binder;
    }
    
    @Override
    public void onCreate()
    {
        //
        PublicTools.createLocalFolad();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);
        
        this.remoteFileService = ServiceFactory.getRemoteFileService();
        this.remoteFolderService = ServiceFactory.getRemoteFolderService();
        this.remoteINodeService = ServiceFactory.getRemoteINodeService();
        this.remoteShareFileService = ServiceFactory.instance(this).getRemoteShareFileService();
        
        this.localFileService = ServiceFactory.instance(this).getLocalFileService();
        this.localShareINodeService = ServiceFactory.instance(this).getLocalShareINodeService();
        
        this.remoteShareFolderService = ServiceFactory.instance(this).getRemoteShareFolderService();
        this.iMailListService = ServiceFactory.instance(getApplicationContext()).getIamIMailListService();
        this.iMusicService = ServiceFactory.getMusicService();
        LogUtil.openLog(CloudDriveService.this);
        super.onCreate();
        
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		List<Integer> notifyList = DAOFactory.instance(this).getUploadFileDao().getNotifyList();
		for(Integer notifyId : notifyList){
			mNotificationManager.cancel(notifyId);
		}
		if(notifyList != null && notifyList.size() > 0){
			DAOFactory.instance(this).getUploadFileDao().deleteAllNotify();
		}
    }
    
    private ILocalFileService getLocalFileService(Context context)
    {
        return ServiceFactory.instance(context).getLocalFileService();
    }
    
    private IlocalFolderService getLocalFolderService(Context context)
    {
        return ServiceFactory.instance(context).getLocalFolderService();
    }
    
    private ILocalShareINodeService getLocalShareINodeService(Context context)
    {
        return ServiceFactory.instance(context).getLocalShareINodeService();
    }
    
    private ILocalShareFileService getLocalShareFileService(Context context)
    {
        return ServiceFactory.instance(context).getLocalShareFileService();
    }
    
    private ILocalShareFolderService getLocalShareFolderService(Context context)
    {
        return ServiceFactory.instance(context).getLocalShareFolderService();
    }
    
    @Override
    @Deprecated
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
    }
    
    @Override
    public void settingServiceAdd()
    {
        
    }
    
    public int readyMusic(Context context, FileFolderInfo path)
    {
        return iMusicService.readyMusic(context, path);
    }
    
    public void playMusic()
    {
        iMusicService.play();
    }
    
    public void pauseMusic()
    {
        iMusicService.pause();
    }
    
    public int getMusicProgress()
    {
        return iMusicService.getProgress();
    }
    
    public void setMusicProgress(int time)
    {
        iMusicService.setProgress(time);
    }
    
    public boolean isMusicPlaying()
    {
        return iMusicService.isMusicPlaying();
    }
    
    public void destoryMusicplayer()
    {
        iMusicService.destory();
    }
    
    @Override
    public List<FileFolderInfo> getFileFolderList(String ownerId, String folderID, String des, int limit, int offset,
        String orderby) throws ClientException
    {
        LogUtil.i(TAG, "Get service list save");
        List<FileFolderInfo> list = this.remoteFileService.getFileFolderList(false,
            CloudDriveService.this,ownerId,
            folderID,
            des,
            limit,
            offset,
            orderby);
        return list;
    }
    
    @Override
    public FileFolderInfo getDatabaseFolderByName(Context context, String ownerId, String folderName)
    {
        // TODO Auto-generated method stub
        LogUtil.i(TAG, "getDatabaseFolderByName");
        return this.getLocalFolderService(context).getDatabaseFolderByName(context, ownerId, folderName);
    }
    
    @Override
    public List<FileFolderInfo> getMoveFolderList(String ownerId, String folderID, String des, int limit, int offset,
        String orderby) throws ClientException
    {
        List<FileFolderInfo> list = this.remoteFileService.getMoveFolderList(CloudDriveService.this,
            ownerId, folderID,
            des,
            limit,
            offset,
            orderby);
        
        return list;
    }
    
    @Override
    public List<FileFolderInfo> getMoveFolderListDB(String ownerId, String folderID, String exception) throws ClientException
    {
        List<FileFolderInfo> list = this.remoteFileService.getMoveFolderDB(CloudDriveService.this,
            ownerId, folderID,
            exception);
        return list;
    }
    
    @Override
    public List<FileFolderInfo> getFileFolderListPage(String ownerId, String folderID, String des, String orderby)
        throws ClientException
    {
        LogUtil.i(TAG, "Get service list save and page");
        List<FileFolderInfo> list = this.remoteFileService.getFileFolderListPage(false,
            CloudDriveService.this,ownerId,
            folderID,
            des,
            orderby,
            null);
        return list;
    }
    
    @Override
    public List<FileFolderInfo> getFileFolderListPage(FileFolderInfo folder)
    {
        LogUtil.i(TAG, "Get service list save");
        List<FileFolderInfo> list = this.remoteFileService.getFileFolderListPage(CloudDriveService.this,
            folder);
        return list;
    }
    
    @Override
    public String deleteAllFile(FileFolderInfo fileFolderInfo) throws ClientException
    {
        String response = null;
        response = this.remoteFileService.deleteFile(fileFolderInfo);
        this.getLocalFileService(CloudDriveService.this).deleteFile(fileFolderInfo);
        return response;
    }
    
    @Override
    public void deleteAllFileAsync(final Context context, final FileFolderInfo fileFolderInfomation, AsyncTaskHandler handler) throws ClientException
    {
    	AsyncTaskResponseInterceptor interceptor = new AsyncTaskResponseInterceptor() {
			@Override
			public void onExecuting() {
			}
			@Override
			public void onSuccess() {
				DirectoryUtil.deleteFileThumbnailPath(context, fileFolderInfomation.getOwnerBy(),
							fileFolderInfomation.getId(), fileFolderInfomation.getName());
				getLocalFileService(CloudDriveService.this).deleteFile(fileFolderInfomation);
				DirectoryUtil.deleteFile(context, fileFolderInfomation);
			}
			@Override
			public void onFailure(ClientException exception) {
			}
    	};
		handler.setInterceptor(interceptor );
        this.remoteFileService.deleteFileAsync(fileFolderInfomation, handler);
    }
    
    @Override
    public String deleteAllFolder(FileFolderInfo folder) throws ClientException
    {
        String response = null;
        response = this.remoteFolderService.deleteFolder(folder);
        this.getLocalFolderService(CloudDriveService.this).deleteFolderAndChild(folder);
        return response;
    }
    
    @Override
    public void deleteAllFolderAync(final FileFolderInfo fileFolderInfomation, AsyncTaskHandler handler) throws ClientException
    {
		AsyncTaskResponseInterceptor interceptor = new AsyncTaskResponseInterceptor() {

			@Override
			public void onExecuting() {
				
			}

			@Override
			public void onSuccess() {
				getLocalFolderService(CloudDriveService.this).deleteFolderAndChild(fileFolderInfomation);
			}

			@Override
			public void onFailure(ClientException exception) {
				
			}
		};
		
		handler.setInterceptor(interceptor );
        this.remoteFolderService.deleteFolderAsyn(fileFolderInfomation, handler);
    }
    
    @Override
    public FolderListResponseV2 searchFolder(FolderSearchRequestV2 request) throws ClientException
    {
        // TODO Auto-generated method stub
        return this.remoteFolderService.searchFolder(request);
    }
    
    @Override
    public FileFolderInfo createFolder(Context context, String ownerId, FolderCreateRequest request) throws ClientException
    {
        return this.remoteFolderService.createFolder(context, ownerId, request);
    }
    
    @Override
    public String moveFile(FileFolderInfo file, FileFolderInfo targetFolder)
        throws ClientException
    {
        String reponse = "";
        
        reponse = this.remoteFileService.moveFile(file, targetFolder);
        this.getLocalFileService(CloudDriveService.this).moveFile(file, targetFolder);
        
        return reponse;
    }
    
    @Override
    public FolderResponse moveFolder(FileFolderInfo folder, FileFolderInfo targetFolder) throws ClientException
    {
    	String targetId = "0";
    	if( targetFolder != null) {
    		targetId = targetFolder.getId();
    	}
        FolderResponse response = this.remoteFolderService.moveFolder(folder, targetFolder);
        this.getLocalFolderService(CloudDriveService.this).moveFolder(folder.getOwnerId(), targetId, folder.getId());
        
        DAOFactory.instance(this).getFolderDao().setChangedFolderId(targetFolder, "1");
        return response;
    }
    
    @Override
    public List<FileFolderInfo> searchInCloud(Context context, int limit, int offset, String name)
        throws ClientException
    {
        List<FileFolderInfo> fileList = this.remoteFileService.searchRemote(context, limit, offset, name);
        return fileList;
    }
    
    @Override
    public List<FileFolderInfo> sortFileFolder(String ownerId, String folderID, String des, int limit, int offset,
        String orderby) throws ClientException
    {
        List<FileFolderInfo> sortlist = this.remoteFileService.getFileFolderList(false,
            CloudDriveService.this,ownerId,
            folderID,
            des,
            limit,
            offset,
            orderby);
        return sortlist;
    }
    
    @Override
    public UserResponseV2 login(String userName, String password) throws ClientException
    {
        return this.remoteFileService.login(CloudDriveService.this, userName, password);
    }
    
    @Override
    public String logout() throws ClientException
    {
        return this.remoteFileService.logout();
    }
    
    @Override
    public FileFolderInfo renameFile(Context context, FileFolderInfo fileInformation, String name) throws ClientException
    {
        FileFolderInfo response = null;
        FileInfoResponseV2 fileInfoResponse = this.remoteFileService.renameFile(fileInformation, name);
        response = this.getLocalFileService(CloudDriveService.this).renameFile( fileInfoResponse, fileInformation);
        return response;
    }
    
    @Override
    public FileFolderInfo renameFolder(FileFolderInfo fileInformation, String name) throws ClientException
    {
        FileFolderInfo response = null;
        FolderResponse folderResponse = this.remoteFolderService.renameFolder(fileInformation, name);
        response = this.getLocalFolderService(CloudDriveService.this).renameFolder(
            folderResponse,
            fileInformation);
        return response;
    }
    
    @Override
    public void syncFolder(FileFolderInfo info, String folderName, String parentId, Handler handler,View itemView)
    {
        this.getLocalFolderService(CloudDriveService.this)
            .syncFolder(info, folderName, parentId, handler,itemView);
    }
    
    @Override
    public void updateFileSyncStatus(int isSync, FileFolderInfo info)
    {
        this.getLocalFileService(CloudDriveService.this).updateSyncStatus(info, isSync);
    }
    
    @Override
    public void updateFolderSyncStatus(int isSync, FileFolderInfo info)
    {
        this.getLocalFolderService(CloudDriveService.this).updateSyncStatus(isSync, info.getOwnerId(), info.getId());
    }
    
    @Override
    public FolderInfo selectFolder(FileFolderInfo fileFolderInfo)
    {
        return this.getLocalFolderService(CloudDriveService.this).getFolderById(fileFolderInfo);
    }
    
    @Override
    public FileInfo selectFile(FileFolderInfo fileFolderInfo)
    {
        return this.getLocalFileService(CloudDriveService.this).getFileById(fileFolderInfo);
    }
    
    @Override
    public List<FileFolderInfo> getSharedFileFolder(boolean autoManualFlag, String folderId, String ownerId,
        String desc, int limite, int offset, String orderBy) throws ClientException
    {
        List<FileFolderInfo> resource = this.remoteINodeService.getInodeFileFolderList(folderId,
            ownerId,
            CloudDriveService.this,
            desc,
            limite,
            offset,
            orderBy);
        return resource;
    }
    
    @Override
    public List<FileFolderInfo> getFileFolderListPage(boolean autoManualFlag, Context context, String ownerId,
        String folderID, String des, String orderby, Handler handler) throws ClientException
    {
        List<FileFolderInfo> resource = this.remoteFileService.getFileFolderListPage(autoManualFlag,
            context,ownerId,
            folderID,
            des,
            orderby,
            handler);
        return resource;
    }
    
    @Override
    public List<FileFolderInfo> getFileFolderListFromServer(final Context context, String ownerId, String folderID,
        String des, String orderby, Handler handler) throws ClientException
    {
    	//get folder infomation except that id is zero
    	if(!"0".equals(folderID)) {
    		//get folder infomation from server
        	FolderResponse folderResponse = remoteFolderService.getFolderResponse(ownerId, folderID);
        	
        	//convert response to local filefolderinfo
        	FolderInfo folderInfomation = new FolderInfo();
        	folderInfomation.valueOf(folderResponse);
        	
        	//notify ui handler information update
        	Message msg = handler.obtainMessage();
        	msg.what = UiConstant.SUCCESS_GET_SERVER_FOLDER_INFOMATION;
        	msg.obj = folderInfomation;
        	msg.sendToTarget();
        	
        	//update databases
        	DAOFactory.instance(context).getFolderDao().updateFolder(folderResponse);
    	}
    	
    	//get sub collection from server
        List<FileFolderInfo> resource = this.remoteFileService.getFileFolderListFromServer(context,
            ownerId, folderID,
            des,
            orderby,
            handler);
        return resource;
    };
    
    @Override
    public List<FileFolderInfo> getSharedFileFolderListPage(boolean autoManualFlag, final Context context,
        String folderID, String des, String orderby, Handler handler, String SharedOwnerId)
        throws ClientException
    {
        List<FileFolderInfo> resource = this.remoteShareFileService.getSharedFileFolderListPage(autoManualFlag,
            context,
            folderID,
            des,
            orderby,
            handler,
            SharedOwnerId);
        return resource;
    }
    
    @Override
    public List<FileFolderInfo> getServerShareResourceList(Context context, String des, String folderId,
        String shareOwnerId, String orderBy) throws ClientException
    {
        List<FileFolderInfo> resource = null;
        resource = this.remoteShareFileService.getServerShareResourceList(context,
            des,
            folderId,
            shareOwnerId,
            orderBy);
        return resource;
    }
    
    @Override
    public List<FileFolderInfo> getBaseServerShareResourceList(String folderId, String ownerId, String desc,
        int limite, int offset, String orderBy) throws ClientException
    {
        List<FileFolderInfo> resource = this.remoteINodeService.getInodeFileFolderList(folderId,
            ownerId,
            CloudDriveService.this,
            desc,
            limite,
            offset,
            orderBy);
        return resource;
    }
    
    @Override
    public List<FileFolderInfo> getDBShareResourceList(String folderId, String ownerId, boolean desc,
        int limite, int offset, String orderBy)
    {
        List<FileFolderInfo> resource = new ArrayList<FileFolderInfo>();
        List<FolderInfo> folderResource = DAOFactory.instance(CloudDriveService.this)
            .getShareFolderDao()
            .getFolderList(folderId, ownerId);
        List<FileInfo> fileResource = DAOFactory.instance(CloudDriveService.this)
            .getShareFileDao()
            .getFileList(folderId, ownerId);
        if (null != folderResource)
        {
            resource.addAll(folderResource);
        }
        if (null != fileResource)
        {
            resource.addAll(fileResource);
        }
        return resource;
    }
    
    @Override
    public List<FileFolderInfo> getBaseDBShareResourceList(String folderId, String ownerId, String desc,
        int limite, int offset, String orderBy)
    {
        List<FileFolderInfo> resource = null;
        try
        {
            resource = this.remoteINodeService.getInodeFileFolderListDB(folderId,
                ownerId,
                CloudDriveService.this,
                desc,
                limite,
                offset,
                orderBy);
        }
        catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
        }
        return resource;
    }
    
    @Override
    public List<FileFolderInfo> getSharedFileFolderList(boolean autoManualFlag, Context context,
        String folderID, String des, int limit, int offset, String orderby, String shareOwnerId)
        throws ClientException
    {
        List<FileFolderInfo> resource = this.remoteShareFileService.getSharedFileFolderList(autoManualFlag,
            context,
            folderID,
            des,
            limit,
            offset,
            orderby,
            shareOwnerId,
            shareOwnerId);
        return resource;
    }
    
    @Override
    public void cancelSyncFolder(final String ownerId, final String folderId, final String folderName)
    {
    	new Thread(new Runnable() {
			@Override
			public void run() {
				cancelSyncInnerFolder(ownerId, folderId, folderName);
			}
	
			private void cancelSyncInnerFolder(String ownerId, String fId, final String fName) {
				ServiceFactory.instance(CloudDriveService.this).getLocalFolderService()
							  .updateSyncStatus(Constant.DOWNLOAD_STATUS_NOCACHE_DB, ownerId, fId);
				FolderListResponseV2 folderListRespone = null;
				try {
					folderListRespone = ServiceFactory.getRemoteFolderService()
					.getFolderListResponse(fId, "DESC", 1000, 0, "modifiedAt");
					for (FileInfoResponseV2 iterable_element : folderListRespone.getFiles()) {
						DownloadTask task = DownloadTaskManager.getTask(iterable_element.getId());
						if(task != null) { 
							task.cancelDownloadTask();
						}
						FileFolderInfo fileInfo = DAOFactory.instance(CloudDriveService.this).getFileDao().getFile(iterable_element);
						if (fileInfo.isSync()) {
							DAOFactory.instance(CloudDriveService.this).getFileDao()
							.updateSyncStatus(iterable_element,Constant.DOWNLOAD_STATUS_NOCACHE_DB);
							DAOFactory.instance(CloudDriveService.this).getFileDao()
							.updateTransStatus(iterable_element, Constant.DOWNLOAD_NON_UPDATE_DB);
							String path = DirectoryUtil.generateFileDownloadPath(CloudDriveService.this, iterable_element.getOwnerBy(), iterable_element.getId(), iterable_element.getName());
							iFileManager mdmTools = FileManagerFactory.getFileManager(CloudDriveService.this);
							mdmTools.deleteFile(path);
						}
					}
				} catch (ClientException e) {
					e.printStackTrace();
				}
				
				if (null != folderListRespone) {
					List<FolderResponse> folderResponseList = folderListRespone.getFolders();
					for (int i = 0; i < folderResponseList.size(); i++) {
						ServiceFactory.instance(CloudDriveService.this).getLocalFolderService()
									  .updateSyncStatus(Constant.DOWNLOAD_STATUS_NOCACHE_DB, folderResponseList.get(i).getOwnerBy(), folderResponseList.get(i).getId());
						FolderResponse folderResponse = folderResponseList.get(i);
						cancelSyncInnerFolder(folderResponse.getOwnerBy(), folderResponse.getId(), folderResponse.getName());
					}
				}
			}
	
		}).start();
    }
    
    @Override
    public void cancelSyncFile(FileFolderInfo info, String fileName)
    {
        this.getLocalFileService(CloudDriveService.this).cancelSyncFile(info, fileName);
    }
    
    @Override
    public boolean downloadFile(String ownerID, final String folderID, final String fileID,
        String authorization, final long fileSize, final String path,
        final IDownloadCallback callback, FileFolderInfo fileinfo)
    {
        if (checkIsRootAndNotify())
        {
            return false;
        }
        else
        {
            
            // DAOFactory
            // .instance(CloudDriveService.this)
            // .getFileDao()
            // .updateSyncStatus(Constant.DOWNLOAD_STATUS_CACHE_DB, fileID);
            DAOFactory.instance(CloudDriveService.this).getFileDao().updateLocalPath(ownerID, fileID, path);
            return DownloadTaskManager.addTask(new DownloadTask(CloudDriveService.this, 
                callback, fileinfo, true));
        }
    }
    
    @Override
    public DownloadTask openFile(String ownerID, final String folderID, final String fileID,
        String authorization, final long fileSize, final String path,
        final ICallback callback, FileFolderInfo fileInformation)
    {
        if (checkIsRootAndNotify())
        {
            return null;
        }
        else
        {
//            DAOFactory.instance(CloudDriveService.this)
//                .getFileDao()
//                .updateSyncStatus(Constant.DOWNLOAD_STATUS_NOCACHE_DB, fileID);
            DAOFactory.instance(CloudDriveService.this).getFileDao().updateLocalPath(ownerID, fileID, path);
            DownloadTask task = new DownloadTask(CloudDriveService.this,
                callback, fileInformation, false);
            DownloadTaskManager.addTask(task);
            return task;
        }
        
    }
    
    @Override
    public boolean downloadFile(DownloadTask downloadTask)
    {
        if (checkIsRootAndNotify())
        {
            return false;
        }
        else
        {
            return DownloadTaskManager.addTask(downloadTask);
        }
    }
    
    @Override
    public Set<DownloadTask> getAllDownloadTask()
    {
        // TODO Auto-generated method stub
        return DownloadTaskManager.getAllTaskes();
    }
    
    @Override
    public Set<DownloadTask> getAllDownloadTask(String folderID)
    {
        return DownloadTaskManager.getAllTaskes(folderID);
    }
    
    @Override
    public DownloadTask getDownloadTask(String fileID)
    {
        // TODO Auto-generated method stub
        return DownloadTaskManager.getTask(fileID);
    }
    
    @Override
    public boolean removeDownloadTask(String fileSha1)
    {
        // TODO Auto-generated method stub
        DownloadTask task = DownloadTaskManager.getTask(fileSha1);
        if (task != null)
        {
            task.cancelDownloadTask();
        }
        return DownloadTaskManager.removeTask(task);
    }
    
    @Override
    public int downloadTaskState(String fileSha1)
    {
        // TODO Auto-generated method stub
        DownloadTask task = DownloadTaskManager.getTask(fileSha1);
        if (DownloadTaskManager.isRunning(task))
        {
            return 0;
        }
        else if (DownloadTaskManager.isWaiting(task))
        {
            return 1;
        }
        return -1;
    }
    
    @Override
    public void downloadThumbnailIcon(String ownerBy, final String fileId, final String iconPath,
        final IDownloadThumbnailCallback callback)
    {
        // TODO Auto-generated method stub
        this.remoteFileService.downloadThumbnailIcon(ownerBy,fileId, iconPath, callback);
    }
    
    // share
    @Override
    public boolean downloadShareFile(String ownerID, final String folderID, final String fileID,
        long startIndex, final long fileSize, final String path,
        final IShareDownloadCallback callback, FileFolderInfo fileFolderInfo, int isInode)
    {
        DAOFactory.instance(CloudDriveService.this)
            .getFileDao()
            .updateSyncStatus(ownerID, fileID, Constant.DOWNLOAD_STATUS_CACHE_DB);
        DAOFactory.instance(CloudDriveService.this).getFileDao().updateLocalPath(ownerID, fileID, path);
        return ShareDownloadTaskManager.addTask(new ShareDownloadTask(CloudDriveService.this, ownerID,
            folderID, fileID, startIndex, fileSize, path, callback,fileFolderInfo, isInode));
    }
    
    @Override
    public ShareDownloadTask openShareFile(String ownerID, final String folderID, final String fileID,
        long startIndex, final long fileSize, final String path,
        final ICallback callback, FileFolderInfo fileFolderInfo, int isInode)
    {
        // DAOFactory.instance(CloudDriveService.this).getFileDao()
        // .updateSyncStatus(Constant.DOWNLOAD_STATUS_NOCACHE_DB, fileID);
        if (isInode == Constant.DOWNLOAD_STATUS_INODE)
        {
            DAOFactory.instance(CloudDriveService.this)
                .getShareINodeDao()
                .updateSyncStatuc(Constant.DOWNLOAD_STATUS_CACHE_DB, fileID, ownerID);
            DAOFactory.instance(CloudDriveService.this)
                .getShareINodeDao()
                .updateLocalPath(fileID, ownerID, path);
        }
        else
        {
            DAOFactory.instance(CloudDriveService.this)
                .getShareFileDao()
                .updateSyncStatus(Constant.DOWNLOAD_STATUS_CACHE_DB, fileID, ownerID);
            DAOFactory.instance(CloudDriveService.this)
                .getShareFileDao()
                .updateLocalPath(fileID, ownerID, path);
        }
        ShareDownloadTask task = new ShareDownloadTask(CloudDriveService.this, ownerID, folderID, fileID,
            startIndex, fileSize, path, callback, fileFolderInfo, isInode);
        ShareDownloadTaskManager.addTask(task);
        return task;
    }
    
    @Override
    public boolean downloadShareFile(ShareDownloadTask downloadTask)
    {
        return ShareDownloadTaskManager.addTask(downloadTask);
    }
    
    @Override
    public Set<ShareDownloadTask> getAllDownloadShareTask()
    {
        // TODO Auto-generated method stub
        return ShareDownloadTaskManager.getAllTaskes();
    }
    
    @Override
    public Set<ShareDownloadTask> getAllDownloadShareTask(String folderID)
    {
        return ShareDownloadTaskManager.getAllTaskes(folderID);
    }
    
    @Override
    public ShareDownloadTask getDownloadShareTask(String fileID)
    {
        // TODO Auto-generated method stub
        return ShareDownloadTaskManager.getTask(fileID);
    }
    
    @Override
    public boolean removeDownloadShareTask(String fileSha1)
    {
        // TODO Auto-generated method stub
        return ShareDownloadTaskManager.removeTask(ShareDownloadTaskManager.getTask(fileSha1));
    }
    
    @Override
    public int downloadShareTaskState(String fileSha1)
    {
        // TODO Auto-generated method stub
        ShareDownloadTask task = ShareDownloadTaskManager.getTask(fileSha1);
        if (ShareDownloadTaskManager.isRunning(task))
        {
            return 0;
        }
        else if (ShareDownloadTaskManager.isWaiting(task))
        {
            return 1;
        }
        return -1;
    }
    
    @Override
    public void downloadShareThumbnailIcon(String ownerID, String iNodeID, String fileId, String iconPath,
        final IDownloadThumbnailCallback callback)
    {
        // TODO Auto-generated method stub
        if (null != iNodeID)
        {
            fileId = iNodeID;
        }
        this.remoteFileService.downloadShareThumbnailIcon(ownerID, fileId, iconPath, callback);
    }
    
    @Override
    public void shareFileSaveMyCloud(String targetOwnerId, String srcOwnerId, String destFolderId, List<String> srcFileIdList,
        final IFileRemoteServiceCallback callback)
    {
        this.remoteFileService.shareFileSaveMyCloud(targetOwnerId, srcOwnerId, destFolderId, srcFileIdList, callback);
    }
    
    @Override
    public void shareFileSaveMyCloud(final String srcOwnerId, String destOwnerId, final String destFolderId,
        final String srcFileId, final IFileRemoteServiceCallback callback)
    {
        this.remoteFileService.shareFileSaveMyCloud(srcOwnerId, destOwnerId, destFolderId, srcFileId, callback);
    }
    
    //
    @Override
    public void uploadFile(String folderID, final String filePath,
        final IUploadCallback uploadCallback)
    {
        //
        UploadTaskManager.addTask(new UploadTask(CloudDriveService.this, folderID,
            filePath, uploadCallback));
    }
    
    @Override
    public void uploadFile(String folderID, final String filePath,
        final InputStream inputStream, final IUploadCallback uploadCallback)
    {
        //
        UploadTaskManager.addTask(new UploadTask(CloudDriveService.this, folderID,
            filePath, inputStream, uploadCallback));
    }
    
    @Override
    public void uploadFile(String folderID, final String filePath,
        String fileEncPath, final InputStream inputStream, final IUploadCallback uploadCallback)
    {
        //
        UploadTaskManager.addTask(new UploadTask(CloudDriveService.this, folderID,
            filePath, fileEncPath, inputStream, uploadCallback));
    }
    
    @Override
    public void uploadFile(UploadTask uploadTask)
    {
        // TODO Auto-generated method stub
        UploadTaskManager.addTask(uploadTask);
    }
    
    @Override
    public void uploadFile(final String folderID, 
        final List<String> filePaths, final IUploadCallback uploadCallback, final Handler uploadHandler)
    {
        // TODO Auto-generated method stub
        for (final String filePath : filePaths)
        {
            // set notifi id
            File file = new File(filePath);
            if (!file.exists())
            {
                break;
            }
            final String name = file.getName();
            LogUtil.i(TAG, "uploadFile... fileName:" + name);
            //
            IUploadCallback callback = new IUploadCallback()
            {
                
                @Override
                public void onSuccess(FileInfoResponseV2 successItem)
                {
                    FileInfo fileInformation = new FileInfo();
                    fileInformation.valueOf(successItem);
                    
                    // TODO Auto-generated method stub
                    LogUtil.i(TAG, "uploadShareFile onSuccess...");
                    Message message = new Message();
                    message.what = 1003;
                    message.obj = fileInformation.getName();
                    handler.sendMessage(message);
                    
                    Message uploadMessage = new Message();
                    uploadMessage.what = 2;
                    uploadMessage.arg1 = uplodadUpdate;
                    uploadMessage.obj = fileInformation;
                    uploadHandler.sendMessage(uploadMessage);
                    
                }
                
                @Override
                public void onStart()
                {
                    // TODO Auto-generated method stub
                    LogUtil.i(TAG, "uploadShareFile start...");
                    handler.sendEmptyMessage(1001);
                }
                
                @Override
                public void onProgress(int currentProgress, long currentSize, long maxSize)
                {
                    handler.sendEmptyMessage(1002);
                }
                
                @Override
                public void onFailure(Throwable t)
                {
                    LogUtil.e(TAG, "uploadShareFile... onFailure:" + t.getLocalizedMessage());
                    handler.sendEmptyMessage(1004);
                }

				@Override
				public void onStop() {
				}

				@Override
				public void onCanceled() {
				}

				@Override
				public void onDettach() {
				}
            };
            UploadTask uploadTask = new UploadTask(CloudDriveService.this, folderID,
                filePath, uploadCallback);
            uploadTask.setCallback(callback);
            boolean isAddSuccess = UploadTaskManager.addTask(uploadTask);
            //
            if (!isAddSuccess)
            {// is Add Fail
                LogUtil.e(TAG, "uploadShareFile... onFailure:"
                    + getString(R.string.upload_failed_noneedupload_again));
                handler.sendEmptyMessage(1005);
            }
            
        }
        // new Thread(new Runnable() {
        // @Override
        // public void run() {
        // // TODO Auto-generated method stub
        // for (String filePath : filePaths) {
        // uploadFile(ownerID, folderID, authorization, filePath,
        // uploadCallback);
        // }
        // }
        // }).start();
    }
    
    //
    @Override
    public Set<UploadTask> getAllUploadTask()
    {
        // TODO Auto-generated method stub
        return UploadTaskManager.getAllTaskes();
    }
    
    @Override
    public Set<UploadTask> getAllUploadTask(String folderID)
    {
        // TODO Auto-generated method stub
        return UploadTaskManager.getAllTaskes(folderID);
    }
    
    @Override
    public UploadTask getUploadTask(String filePath)
    {
        // TODO Auto-generated method stub
        return UploadTaskManager.getTask(filePath);
    }
    
    @Override
    public boolean isServiceUpdate(Context context, FileFolderInfo info) throws ClientException
    {
        return this.remoteFolderService.isUpdate(context, info);
    }
    
    public RefreshToken refreshToken()
    {
        LogUtil.i(TAG, "refreshToken");
        RefreshToken newToken = null;
        if (checkIsRootAndNotify())
        {// root
            return newToken;
        }

		SharedPreferences settings = getSharedPreferences(ClientConfig.settings, MODE_APPEND);
		String refreshToken = settings.getString(ClientConfig.REFRESHTOKEN, "");
        try
        {
        	if(!StringUtil.isBlank(refreshToken))
        	{
        		newToken = userClient.refreshToken(refreshToken);
        	}
        }
        catch (ClientException e)
        {
            LogUtil.e(TAG, "e:" + e.getStatusCode());
        }
        return newToken;
    }
        
    private BroadcastReceiver mReceiver = new BroadcastReceiver()
    {
        
        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
            {
                LogUtil.i(TAG, "mReceiver network broadcast internetState...");
                if (0l == oldSystemTime)
                {
                    oldSystemTime = System.currentTimeMillis();
                }
                else
                {
                    long curSystemTime = System.currentTimeMillis();
                    if (curSystemTime - oldSystemTime < 1 * 1000)
                    {
                        LogUtil.i(TAG, "mReceiver network broadcast internetState call is very busy...");
                        return;
                    }
                    else
                    {
                        oldSystemTime = curSystemTime;
                    }
                }
                LogUtil.i(TAG, "mReceiver network broadcast internetState need call internet state...");
                Message msg = new Message();
                msg.what = internetState;
                handler.sendMessage(msg);
            }
        }
    };
    
    private BroadcastReceiver reloginReceiver = new BroadcastReceiver()
    {
        
        @Override
        public void onReceive(Context arg0, Intent arg1)
        {
            // TODO Auto-generated method stub
            SharedPreferences settings = getSharedPreferences(ClientConfig.settings, MODE_APPEND);
            if (settings.getBoolean(ClientConfig.INTERNETSTATE, false))
            {
                LogUtil.i(TAG, "reloginReceiver refresh token broadcast refreshToken...");
                Message msg = new Message();
                msg.what = refreshToken;
                handler.sendMessageDelayed(msg, 1000);
            }
            
        }
    };
    
    @Override
    public synchronized void upgradeCloudDrive(IUpdateStateChangeListener onUpdateStateChangeListener,ClientInfoResponseV2 versionInfo,boolean makeTxt)
    {
        
        UpgradeUtils upgradeUtils = new UpgradeUtils(CloudDriveService.this);
        if (onUpdateStateChangeListener != null)
        {
            upgradeUtils.setOnUpdateStateChangeListener(onUpdateStateChangeListener);
        }
        else
        {
            upgradeUtils.setOnUpdateStateChangeListener(null);
        }
        upgradeUtils.upgradeCloudDrive(versionInfo,makeTxt);
    }
    
    @Override
    public void updateTransStatus(FileFolderInfo node, int trans_status)
    {
        DAOFactory.instance(CloudDriveService.this).getFileDao().updateTransStatus(node, trans_status);
    }
    
    /**
     * handle refresh token
     */
    private Handler handler = new Handler()
    {
        
        public void handleMessage(android.os.Message msg)
        {
            
            switch (msg.what)
            {
            /** intertnet state */
                case internetState:
                    getInternetState();
                    break;
                /** refreshToken */
                case refreshToken:
                    LogUtil.i(TAG, "start refreshToken...");
                    // if (controller.getNetworkState()) {
                    // new Thread(new Runnable() {
                    // @Override
                    // public void run() {
                    // // TODO Auto-generated method stub
                    //
                    // refreshToken();
                    //
                    // }
                    // }).start();
                    // }
                    break;
                case failedToAuthen:
                    LogUtil.e(TAG, "login Authen Fail!");
					if (ShareDriveApplication.getInstance()
							.getWifiController().getNetworkState()) {
						new Thread(new Runnable() {
							@Override
							public void run() {	
								loginIn(PublicTools.getLoginUserName(CloudDriveService.this),
										PublicTools.getLoginUserPassFail(CloudDriveService.this),
										CloudDriveService.this.operateExceptionHandlers);
	
							}
						}).start();
					}
                    break;
                
                /** network is not availible */
                case networkIsNotAvailible:
                    LogUtil.e(TAG, "network is not availible");
                    // Toast.LENGTH_SHORT).show();
                    
                    break;
                
                case loginException:
                    
                    break;
                
                case 1001:
                    
                    break;
                case 1002:
                    
                    break;
                case 1003:
                    LogUtil.i(TAG, "handler success ready insert database...");
                    String uploadName = (String) msg.obj;
                    Toast.makeText(CloudDriveService.this,
                		"["
                         + uploadName
                         + "]"
                         + CloudDriveService.this.getResources()
                                .getString(R.string.fileListadapter_upload_success),
                        Toast.LENGTH_SHORT).show();
                    break;
                case 1004:
                    Toast.makeText(CloudDriveService.this,
                        CloudDriveService.this.getResources()
                            .getString(R.string.fileListadapter_upload_failed),
                        Toast.LENGTH_SHORT).show();
                    break;
                case 1005:
//                    Toast.makeText(CloudDriveService.this,
//                        CloudDriveService.this.getResources()
//                            .getString(R.string.upload_failed_noneedupload_again),
//                        Toast.LENGTH_SHORT).show();
                    break;
                /** default exception */
                default:
                    
                    break;
            }
            
        };
    };
    
    private Handler operateExceptionHandlers = new Handler()
    {
        public void handleMessage(Message msg)
        {
            String code = (String) msg.obj;
            switch (msg.what)
            {
            /** 901*/
                case ExceptionConstant.access_Server_Failed:
                    
                    break;
                /** 401  */
                case ExceptionConstant.Authorized_Code:
                    if (ExceptionConstant.unauthorized.equalsIgnoreCase(code))
                    {
                        Toast.makeText(CloudDriveService.this,
                            CloudDriveService.this.getString(R.string.passwordiswrong) + "(" + msg.what + ")",
                            Toast.LENGTH_SHORT)
                            .show();
                    }
                    else if (ExceptionConstant.clientunauthorized.equalsIgnoreCase(code))
                    {
                        ActivityTaskManager.getInstance().closeAllActivity();
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setClass(CloudDriveService.this, LoginActivity.class);
                        startActivity(intent);
                    }
                    
                    break;
                /** 409  */
                case ExceptionConstant.conflict_Code:
                    
                    break;
                /** 403  */
                case ExceptionConstant.Forbidden_Code:
                    
                    break;
                /** 507*/
                case ExceptionConstant.insufficient_storage_Code:
                    
                    break;
                /** 500  */
                case ExceptionConstant.InternalServerError_Code:
                    
                    break;
                /** 405 */
                case ExceptionConstant.Method_Code:
                    
                    break;
                /** 400 */
                case ExceptionConstant.Request_Code:
                    
                    break;
                /** 412 */
                case ExceptionConstant.requests_Code:
                    
                    break;
                /** 404  */
                case ExceptionConstant.Resource_Code:
                    
                    break;
                /** 503 Service Unavailable  */
                case ExceptionConstant.Service_Unavailable:
                    
                    /** 417*/
                case ExceptionConstant.transaction_Code:
                    
                    break;
                
//                case 1000://upgrade
//                    upgradeCloudDrive(null);
//                    break;
                /** default */
                default:
                    break;
            }
        };
    };
    
    @Override
    public void loginIn(String userName, String passWord, Handler handler)
    {
        if (null == handler)
        {
            handler = CloudDriveService.this.handler;
        }
        try
        {
            LogUtil.i(TAG, "start loginIn()");
            String serverAddress = ShareDriveApplication.getInstance().getServerAddress();
            CommonClient.getInstance().setServiceURL(serverAddress);
            login(userName, passWord);
        }
        catch (ClientException e)
        {
        	if(e.getStatusCode() == ErrorConstant.CLIENT_ERROR_LOGIN_INFO) {
        		if (null != userName && 0 < userName.length()) {
					if (null == passWord || 0 >= passWord.length()) {
						Message msg = new Message();
						msg.what = loginException;
						msg.arg1 = 404;
						handler.sendMessage(msg);
					}
				} else {
					Message msg = new Message();
					msg.what = loginException;
					msg.arg1 = 404;
					handler.sendMessage(msg);
				}
        	} else {
	        	 Message msg = new Message();
	             msg.what = e.getStatusCode();
	             msg.arg1 = sendFromLogin;
	             String code = "";
	             if (null != e.getCode())
	             {
	                 code = e.getCode();
	             }
	             msg.obj = code;
	             handler.sendMessage(msg);
        	}
        }
    }
    
    public void getInternetState()
    {
        // Log.e("relogin_text", "getInternetState");
    	ShareDriveApplication.getInstance()
			.getWifiController().is3GorWifi();
        LogUtil.i(TAG, "wifi_type:" + ShareDriveApplication.getInstance()
				.getWifiController().getWifiType());
        SharedPreferences settings = getSharedPreferences(ClientConfig.settings, MODE_APPEND);
        Editor editor = settings.edit();
        if (ShareDriveApplication.getInstance()
				.getWifiController().networkIsAvailible())
        {
            // Log.e("relogin_text", "networkIsAvailible");
            Message msg = new Message();
            msg.what = refreshToken;
            handler.sendMessageDelayed(msg, 1000);
            editor.putBoolean(ClientConfig.INTERNETSTATE, true);
            Intent stateIntent = new Intent(Constant.REFRESH_ALLFILESTATE_ACTION);
            stateIntent.putExtra("statecode", 1);
            sendBroadcast(stateIntent);
            
            Intent shareStateIntent = new Intent(Constant.STATE_SHARED_FRO_ME);
            shareStateIntent.putExtra("statecode", 1);
            sendBroadcast(shareStateIntent);
        }
        else
        {
            LogUtil.i(TAG, "No internet enable!");
            editor.putBoolean(ClientConfig.INTERNETSTATE, false);
            Message msg = new Message();
            msg.what = networkIsNotAvailible;
            handler.sendMessage(msg);
            Intent stateIntent = new Intent(Constant.REFRESH_ALLFILESTATE_ACTION);
            stateIntent.putExtra("statecode", 0);
            sendBroadcast(stateIntent);
            
            Intent shareStateIntent = new Intent(Constant.STATE_SHARED_FRO_ME);
            shareStateIntent.putExtra("statecode", 0);
            sendBroadcast(shareStateIntent);
        }
        editor.commit();
    }
    
    @Override
    public FileInfo gainOnlyOne(String ownerId, String id)
    {
        return (FileInfo) DAOFactory.instance(CloudDriveService.this).getFileDao().getFile(ownerId, id);
    }
    
    @Override
    public void updateLocalPath(String ownerId, String id, String localPath)
    {
        DAOFactory.instance(CloudDriveService.this).getFileDao().updateLocalPath(ownerId, id, localPath);
    }
    
    @Override
    public List<FolderInfo> selectParentIdAllFolder(String ownerId, String parentID)
    {
        return DAOFactory.instance(CloudDriveService.this).getFolderDao().getFolderList(ownerId, parentID);
    }
    
    @Override
    public List<FileInfo> selectParentIdAllFile(String ownerId, String parentID)
    {
        return DAOFactory.instance(CloudDriveService.this).getFileDao().getFileList(ownerId, parentID);
    }
    
    @Override
    public FileFolderInfo selectShareINode(String fileId, String ownerId)
    {
        // TODO Auto-generated method stub
        return this.getLocalShareINodeService(CloudDriveService.this).getFileById(fileId, ownerId);
    }
    
    @Override
    public FolderInfo selectShareFolder(String fileId, String ownerId)
    {
        // TODO Auto-generated method stub
        return this.getLocalShareFolderService(CloudDriveService.this).getFolderById(fileId, ownerId);
    }
    
    @Override
    public FileInfo selectShareFile(String fileId, String ownerId)
    {
        // TODO Auto-generated method stub
        return this.getLocalShareFileService(CloudDriveService.this).getFileById(fileId, ownerId);
    }
    
    @Override
    public void clearCloudDriveCache(final Handler handler)
    {
        // TODO Auto-generated method stub
        this.getLocalFileService(CloudDriveService.this).clearCloudDriveCache(handler);
    }
    
    @Override
    public void getCloudDriveCache(Handler handler)
    {
        // TODO Auto-generated method stub
        this.getLocalFileService(CloudDriveService.this).getCloudDriveCache(handler);
    }
    
    public boolean checkIsRootAndNotify()
    {
        if (PublicTools.mdmRootCheck())
        {
            // dialog
            try
            {
                Dialog dialog = buildNowIsRootDialog();
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(false);
                dialog.show();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    
    public Dialog buildNowIsRootDialog()
    {
        final Context context = getApplicationContext();
        Dialog dialog = CloudDriveDialogUtil.getCloudDriveDialog(this,
            R.string.root_message,
            new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    new Thread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            
                            String res = "";
                            
                            try
                            {
                                res = logout();
                                LogUtil.e(TAG, "loginout_res:" + res);
                            }
                            catch (ClientException e)
                            {
                                // TODO Auto-generated catch block
                                LogUtil.e(TAG, "statueCode:" + e.getStatusCode());
                                e.printStackTrace();
                            }
                            Message msg0 = Message.obtain(handler, new Runnable()
                            {
                                
                                @Override
                                public void run()
                                {
                                    // Context context =
                                    // context.getApplicationContext();
                                    PublicTools.clearData(context);
                                    Toast.makeText(context,
                                        context.getString(R.string.setting_clear_ok),
                                        Toast.LENGTH_LONG).show();
                                    SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings,
                                        Context.MODE_APPEND);
                                    Editor editor = settings.edit();
                                    editor.putBoolean(ClientConfig.AUTOLOGIN, false);
                                   
                                    editor.putString(ClientConfig.USERNAME, "");
                                    editor.putString(ClientConfig.CURRENTUSERNAME, "");
                                    
                                    editor.putString(ClientConfig.CURRENTPASSWORD, "");
                                    editor.putString(ClientConfig.LOGINPASSWORD, "");
                                    
                                    editor.commit();
                                    
                                    ShareDriveApplication.getInstance().setAuthorization(null);
                                    ShareDriveApplication.getInstance().setWnerID(null);
                                    PublicTools.setExpiredAt(CloudDriveService.this,0);
                                    
                                    PollingAlarmUtils.stopPollingService(context, 1, "relogin");
                                    Intent intent = new Intent();
                                    intent.setClass(context, LoginActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    ActivityTaskManager.getInstance().closeAllActivity();
                                    context.startActivity(intent);
                                    
                                }
                            });
                            handler.sendMessage(msg0);
                        }
                        
                    }).start();
                    
                }
            },
            null);
        return dialog;
    }
    
    @Override
    public void loginBackGround(Handler handler)
    {
        // TODO Auto-generated method stub
        LogUtil.i(TAG, "loginBackGround start...");
        if (checkIsRootAndNotify())
        {// root
            LogUtil.i(TAG, "loginBackGround check device root, clean data...");
            return;
        }
        // Log.e("relogin_text", "refreshToken");
        if (null != ShareDriveApplication.getInstance().getAuthorization())
        {
            LogUtil.i(TAG, "loginBackGround authorization has value....");
            // Log.e("relogin_text", "refresh_token_in time:");
            SharedPreferences settings = getSharedPreferences(ClientConfig.settings, MODE_APPEND);
            Editor editor = settings.edit();
//            long savedMills = settings.getLong(ClientConfig.EXPIREDAT, 0);
//            
//            long currentMills = System.currentTimeMillis();
//            
//            LogUtil.i(TAG, "currentMills:" + currentMills);
//            LogUtil.i(TAG, "savedMills:" + savedMills);
//            LogUtil.e(TAG, "currentMills - savedMills:" + (currentMills - savedMills));
//            if (0 > currentMills - savedMills)
            if(!PublicTools.isAuthiorzationGotoTimeout(this))
            {
                Message msg = new Message();
                msg.what = 1;
                handler.sendEmptyMessage(msg.what);
                LogUtil.i(TAG, "loginBackGround authorization has value, no need to refresh token...");
            }
            else
            {
                LogUtil.e(TAG, "loginBackGround authorization is null that need to loginInBackGround...");
                loginInBackGround(handler);
            }
        }
        else
        {
            LogUtil.e(TAG, "loginBackGround authorization is null that need to loginInBackGround...");
            loginInBackGround(handler);
        }
    }
    
    /***
     * @param handler
     * @param what
     */
    private void loginInBackGround(Handler handler)
    {
        LogUtil.i(TAG, "loginBackGround start...");
        try
        {
            LogUtil.i(TAG, "loginInBackGround user data exist...");
            UserResponseV2 response = login(PublicTools.getLoginUserName(CloudDriveService.this),
                PublicTools.getLoginUserPassFail(CloudDriveService.this));
            
            if (null != response)
            {
                LogUtil.i(TAG, "loginInBackGround login response is success...");
                Message msg = new Message();
                msg.what = 1;
                handler.sendEmptyMessage(msg.what);
            }
            else
            {
                LogUtil.e(TAG, "loginInBackGround login response is null...");
            }
        }
        catch (ClientException e)
        {
        	if(e.getStatusCode() == ErrorConstant.CLIENT_ERROR_LOGIN_INFO) {
        		LogUtil.e(TAG, "loginBackGround user data is null, jump to login...");
        		Message msg = new Message();
        		msg.what = 8;
        		handler.sendMessage(msg);
        	} else {
	            LogUtil.e(TAG, "loginBackGround exception_Code:" + e.getStatusCode());
	            Message msg = new Message();
	            msg.what = e.getStatusCode();
	            handler.sendMessage(msg);
        	}
            e.printStackTrace();
        }
    }

	private String computeUserId(UserResponseV2 response) {
		String userId = response.getCloudUserId() == null ? response.getUserId() : response.getCloudUserId();
		return userId;
	}
    
    @Override
    public List<FileFolderInfo> getFileFolderListFromDB(Context context, String ownerId, String folderID, String des,
        String orderby, Handler handler) throws ClientException
    {
        // TODO Auto-generated method stub
        List<FileFolderInfo> resource = this.localFileService.getFileFolderInfos(context,
            ownerId, folderID,
            des,
            orderby);
        return resource;
    }
    
    @Override
    public List<FileFolderInfo> searchInDB(String ownerId, String fileName, Context context)
    {
        // TODO Auto-generated method stub
        return this.localFileService.searchInDB(ownerId, fileName, context);
    }
    
    @Override
    public long insertUploadData(FileInfoResponseV2 fileInfoResponse)
    {
        // TODO Auto-generated method stub
        return this.getLocalFileService(CloudDriveService.this).insertFile(fileInfoResponse);
    }
    
    public void creatMobileForbiddenDialog()
    {
        // AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // builder.setIcon(android.R.drawable.ic_dialog_alert)
        // .setTitle(R.string.alert)
        // .setMessage(R.string.device_disable)
        // .setPositiveButton(getString(R.string.window_dialog_ok_bt),
        // new OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface dialog,
        // int which) {
        // dialog.dismiss();
        //
        // }
        // });
        // Dialog dialog = builder.create();
        // dialog.getWindow()
        // .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        // dialog.setCanceledOnTouchOutside(false);
        // dialog.setCancelable(false);
        // dialog.show();
        
        Dialog dialog = CloudDriveDialogUtil.getCloudDriveDialog(this,
            R.string.device_disable,
            new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    
                }
            },
            null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }
    
    /***
     * @param context
     */
    public void shutUpApp()
    {
        if (!ActivityTaskManager.getInstance().isEmpty())
        {
            ActivityTaskManager.getInstance().closeAllActivityEnhance(ViewActivity.TAG);
        }
    }
    
    /***
     * @return
     */
    @Override
    public boolean getResourceIsChange()
    {
        return remoteFileService.getResourceIsChange();
    }
    
    @Override
    public boolean getInodeResourceIsChange()
    {
        // TODO Auto-generated method stub
        return remoteINodeService.getInodeIsChange();
    }
    
    @Override
    public boolean getShareResourceIsChange()
    {
        return remoteShareFileService.getShareResourceIsChanged();
    }
    
    @Override
    public void rejectShare(String authorization, long ownerId, long iNodeId) throws ClientException
    {
        remoteShareFileService.rejectShare(authorization, ownerId, iNodeId);
    }
    
    @Override
    public FileInfoResponseV2 copyFile(FileFolderInfo copyedFileFolderInfo, 
    		FileFolderInfo targetFolder) throws ClientException
    {
    	FileInfoResponseV2 response = remoteShareFileService.copyFileToTarget(copyedFileFolderInfo, targetFolder);
        
    	DAOFactory.instance(this).getFileDao().insertFile(response);
        DAOFactory.instance(this).getFolderDao().setChangedFolderId(targetFolder, "1");
        
        return response;
    }
    
    @Override
    public FolderResponse copyFolder(FileFolderInfo savedFileFolderInfo, FileFolderInfo targetFolder) throws ClientException
    {
    	FolderResponse response = remoteShareFolderService.copyFolderToTarget(savedFileFolderInfo, targetFolder);
        
        DAOFactory.instance(this).getFolderDao()
        		  .insertFolder(response, Constant.DOWNLOAD_STATUS_NOCACHE_DB);
        DAOFactory.instance(this).getFolderDao().setChangedFolderId(targetFolder, "1");
        
        return response;
    }
    
    @Override
    public void deleteInodeFileOrFolder(String folderId, String ownerId)
    {
        // TODO Auto-generated method stub
        localShareINodeService.deleteFileOrFolder(folderId, ownerId);
    }
    
    @Override
    public List<ADUser> dbQueryMailList(String keyText)
    {
        return iMailListService.selectMailList(keyText);
    }
    
    @Override
    public void dbInsertMailList(List<ADUser> mailList) throws Exception
    {
        iMailListService.dbInsertMailList(mailList);
    }
    
    @Override
    public List<UserInfoV2> svQueryMailList(String keyText) throws ClientException
    {
        if (remoteMailListService == null)
        {
            remoteMailListService = new RemoteMailListService();
        }
        return remoteMailListService.queryMailList(keyText);
    }
    
    @SuppressWarnings("null")
    @Override
    public List<UserInfoV2> queryMailList(String keyText) throws ClientException, Exception
    {
        List<UserInfoV2> adUserlist = null;
        
        adUserlist = svQueryMailList(keyText);
        return adUserlist;
    }
    
    @Override
    public List<FileInfo> getDownloadFileList()
    {
//        // TODO Auto-generated method stub
//        List<FileInfo> fileList = DAOFactory.instance(CloudDriveService.this)
//            .getDownloadFileDao()
//            .getDownloadFileList();
        return null;
    }
    
    @Override
    public List<UploadObject> getUploadFileList()
    {
        // TODO Auto-generated method stub
        return DAOFactory.instance(CloudDriveService.this).getUploadFileDao().getUploadFileList();
    }
    
    @Override
    public void deleteDownloadFile(String fileID)
    {
        // TODO Auto-generated method stub
        DAOFactory.instance(CloudDriveService.this).getDownloadFileDao().deleteFile(fileID,
        		ShareDriveApplication.getInstance().getWnerID());
    }
    
    @Override
    public void updateDownloadState(String id, int transStatus)
    {
        // TODO Auto-generated method stub
        DAOFactory.instance(CloudDriveService.this).getDownloadFileDao().updateDownloadState(id,
        		ShareDriveApplication.getInstance().getWnerID(), transStatus);
    }
    
    @Override
    public String getServerAddress(String type) throws ClientException
    {
        // TODO Auto-generated method stub
        return remoteFileService.getServerAddress(type).getServerUrl();
    }
    
    @Override
    public List<LinkInfoV3> getLink(FileFolderInfo fileInformation) throws ClientException
    {
    	List<LinkInfoV3> linkInfo = this.remoteFolderService.getLink(fileInformation);
        return linkInfo;
    }
    
    @Override
    public boolean isComplexLinkCode(String authorization) throws ClientException
    {
    	return this.remoteFolderService.isComplexLinkCode(authorization);
    }
    
    @Override
    public LinkInfoV2 setLink(FileFolderInfo fileInformation) throws ClientException
    {
        LinkInfoV2 linkInfo = this.remoteFolderService.createLink(fileInformation);
        if (fileInformation.getIsFile() == 1)
        {
            DAOFactory.instance(CloudDriveService.this)
                .getFileDao()
                .setShareLink(fileInformation, true);
        }
        else
        {
            DAOFactory.instance(CloudDriveService.this)
                .getFolderDao()
                .setFolderLink(fileInformation, true);
        }
        
        return linkInfo;
    }
    
    @Override
    @Deprecated
	public void deleteLink(FileFolderInfo fileInformation)
			throws ClientException {
//    	this.remoteFolderService.deleteLink(fileInformation);
        if (fileInformation.getIsFile() == 1)
        {
            DAOFactory.instance(CloudDriveService.this)
                .getFileDao()
                .setShareLink(fileInformation, false);
        }
        else
        {
            DAOFactory.instance(CloudDriveService.this)
                .getFolderDao()
                .setFolderLink(fileInformation, false);
        }
	}
    
    @Override
    public LinkInfoV2 updateLink(FileFolderInfo fileInformation, LinkCreateRequestV2 linkRequest)
        throws ClientException
    {
        LinkInfoV2 linkInfo = this.remoteFolderService.updateLink(fileInformation, linkRequest);
        return linkInfo;
    }

	@Override
	public boolean isServiceFileUpdate(Context context, FileFolderInfo info)
			throws ClientException {
        return this.remoteFileService.isFileUpdate(context, info);
	}

}
